package com.ok.common.ext

import android.widget.ImageView
import androidx.databinding.BindingAdapter
import coil.load
import coil.request.repeatCount
import coil.size.Scale
import coil.transform.CircleCropTransformation
import coil.transform.RoundedCornersTransformation
import coil.transform.Transformation
import com.ok.common.enum.ShapeType

fun ImageView.loadImage(
    url: Any,
    placeholder: Int? = 0,
    error: Int? = 0,
    shapeType: ShapeType? = ShapeType.NONE,
    radius: Float? = 0f,
    duration: Int? = 0,
    repeatCount: Int? = -1,
    grayScale: Boolean? = false,
    transformation: Transformation? = null
) {
    load(url) {
        placeholder(placeholder!!)
        error(error!!)
        crossfade(true)
        transformation?.let {
            transformations(it)
        }
        repeatCount?.let { repeatCount(it) }
        if (duration!! > 0L) crossfade(duration)
        if (grayScale!!) {
            // TODO: 这边灰度待完善
        }
        when (shapeType) {
            ShapeType.ROUND -> {
                transformations(CircleCropTransformation())
                scale(Scale.FIT)
            }

            ShapeType.RECTANGLE -> {
                transformations(
                    RoundedCornersTransformation(
                        radius = radius!!
                    )
                )
            }

            else -> {}
        }
    }
}

@BindingAdapter(value = ["url", "placeholder", "error", "shape_type", "radius"], requireAll = false)
fun ImageView.loadImageBinding(
    url: Any,
    placeholder: Int? = 0,
    error: Int? = 0,
    shapeType: ShapeType? = ShapeType.NONE,
    radius: Float? = 0f
) {
    loadImage(url, placeholder, error, shapeType, radius)
}
